#include<iostream>
#include<cstdio>
#include<unistd.h>
#include<cstdlib>
#include<string>
#include<cstring>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

const int N = 2;
const int NUM = 1024;

void Write(int wfd)
{
    string s = "I am a child";
    pid_t pid = getpid();
    int num = 0; //实现变化写入

    char buffer[NUM]; //用户级别缓冲区
    while(true)
    {
        sleep(1);
        buffer[0] = 0; //提醒阅读代码的人，将buffer当作是一个字符串
        snprintf(buffer, sizeof(buffer), "%s-%d, %d", s.c_str(), pid, num++); //序列化
        //写入：
        write(wfd, buffer, strlen(buffer)); //strlen() 不需要+1
    }

}

void Read(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0] = 0;
        ssize_t len = read(rfd, buffer, sizeof(buffer));
        if(len > 0)
        {
            buffer[len] = 0; // 最后一个位置'\0';
            printf("father[%d] get a message: %s\n", getpid(), buffer);
        }
        else if(len == 0) break; //len == 0代表读取到文件的末尾位置！在当前情形下是：子进程没有继续先写入了
        else break;
    }
}

int main()
{
    int pipefd[N] = { 0 };
    int ret = pipe(pipefd);
    if(ret < 0) return 1;

    //child - w， father - r
    int retid = fork();
    if(retid < 0) return 2;
    else if(retid == 0)
    {
        //子进程 - w
        close(pipefd[0]); //关闭读文件
        
        Write(pipefd[1]); //写操作
        
        close(pipefd[1]); //关闭写文件
        exit(0); //退出
    }
    //父进程 - r
    close(pipefd[1]); //关闭写文件
    
    Read(pipefd[0]); //读操作
    int status = 0;
    int w = waitpid(retid, &status, 0);
    if(w < 0) return 3;
    else
    {
        cout << "wait success" << endl;
    }
    close(pipefd[0]); //关闭读文件
    return 0;
}
